<style scoped>
  .clientOrderGoods{
    margin-right: 0.5vw;
    padding: 0 15px;
    background-color: white;
    height: 95vh;
    position: relative;
  }
  .cog-top{
    display: flex;
    padding: 1.5vh 0;
    border-bottom: 2px solid #f4f4f4;
  }
  .cog-top p:first-child{
    margin: 3px 6px 0 0;
    display: inline-block;
    white-space:nowrap;
  }
  .cog-top p:not(:first-child){
    margin: 3px 6px 0 12px;
    display: inline-block;
    white-space:nowrap;
  }
  .top-inp{
    width: 160px;
  }
  .cog-btn{
    display: flex;
    justify-content: space-between;
    padding: 1.5vh 0;
  }
  .footView span{
    float: left;
    margin-right: 48px;
    line-height: 6vh;
    font-size: 14px;
  }
  .footView span i{
    margin-right: 5px;
  }
</style>

<style>
  .clientOrderGoods .cog-top .el-input__inner{
    height: 30px;
  }
  .clientOrderGoods .cog-btn .el-checkbox.is-bordered{
    padding: 5px 10px 0 10px;
    height: 30px;
  }
  .clientOrderGoods .el-input__icon{
    line-height: 30px;
  }
  .clientOrderGoods .cog-btn .el-button{
    margin: 0 10px 0 0;
  }
  .clientOrderGoods .el-table__footer td {
  height: 26px;
}
</style>

<template>
  <div class="clientOrderGoods">
    <!-- 客户订货 -->
    <div class="cog-top">
      <p>配货方式</p>
      <el-select class="top-inp" v-model="cooperateWay">
        <el-option v-for="item in cooperateWayList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>客户</p>
      <el-input style="width:60px;margin-right:10px;" v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"></el-input>
      <el-select style="width:100px;" v-model="customerName" @change="e=>{this.customerNo=e}" :disabled="jxAgent">
        <el-option v-for="item in customerList" :key="item.value" :label="item.label" :value="item.value">
          <span style="float:left">{{item.value}}</span>
          <span style="float:right">{{item.label}}</span></el-option>
      </el-select>
      <p>订货日期</p>
      <el-date-picker class="top-inp" v-model="inputDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
      <p>订货序号</p>
      <el-input class="top-inp" v-model="sequence" disabled></el-input>
      <p>备注</p>
      <el-input style="width:350px;" v-model="remark"></el-input>
    </div>
    <div class="cog-btn">
      <div>
        <el-button @click="create" type="primary" icon="el-icon-plus">新建</el-button>
        <el-button @click="Affirm" icon="el-icon-circle-check" :disabled="isConfirm">确认</el-button>
        <!-- <el-button @click="()=>{this.showpwd=true}" icon="el-icon-edit-outline">改单</el-button> -->
        <el-button @click="printConfirm" icon="el-icon-printer">列印</el-button>
        <!-- <el-button icon="el-icon-download">CSV导入</el-button>
        <el-button icon="el-icon-download">货号纵向导入</el-button> -->
        <div class="dr">
          <i class="el-icon-download"></i>CSV导入
          <input ref="upload1" accept=".csv" class="outputlist_upload" type="file" @change="readExcel">
        </div>

        <div class="dr">
          <i class="el-icon-download"></i>货号导入
          <input ref="upload2" accept=".xls, .xlsx" class="outputlist_upload" type="file" @change="readExcel">
        </div>
        <el-button @click="dele" icon="el-icon-delete" :disabled="isConfirm">删除</el-button></div>
      <div>
        <span style="margin: 0 30px">合计：{{total}}</span>
        <el-checkbox v-model="checked" border>二维</el-checkbox>
      </div>
    </div>
    <el-table :header-cell-style="{background:'#f4f4f4',padding:0,height:'30px'}" :cell-style="{padding:0,height:'26px'}" :data="tableData" style="width: 100%" height="75vh" ref="table" show-summary :summary-method="getSummaries">
      <template v-for="i in this.Hlist">
        <el-table-column :key="i.prop" :prop="i.prop" :label="i.label" :width="i.width" show-overflow-tooltip></el-table-column>
      </template>
    </el-table>
    <new-add v-show="newadd" :sendData="sendData" :customerL="customerList" :pageSession="pageSession" :flag="newadd" @closeAdd="()=>{this.newadd=false}" @saveNew="saveAdd" @inpNumChange="()=>{this.inpList = this.getInput()}"></new-add>
    <!-- 改单密码验证 -->
    <verify-password v-if="showpwd" @closepwd="()=>{this.showpwd=false}" @showRevision="showRevision"></verify-password>
    <change-od v-show="showChangeOd" :flag="showChangeOd" :sequence="sequence" :customerList="customerList" @closeReviSion="()=>{this.showChangeOd=false}"></change-od>
    <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span>
        <span>操作员：{{operator}}</span>
        <!-- <span>记录数：{{amount}}</span> -->
      </div>
    </foot-view>
    <print-area v-show=false isInput='订' isVendor="客户" :manufacturerName="printVendorName" :principal="principal" :phone="phone" :address="address" :remark="remark" :inputSequence="sequence" :jxQuarter="jxQuarter" :inputDate="printDate" :printTotal="printTotal" :printMoney="printMoney" :printStyle="printStyle" :printSellingPrice="printSellingPrice" :shipType="cooperateWay" :cellphone="cellphone" :companyName="companyName" :companyPhone="companyPhone"></print-area>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS')

import verifyPassword from '../../../components/VerifyPassword'
import footView from '../../../components/FootView'
import newAdd from './childComp/NewAdd'
import changeOd from './childComp/ChangeOd'
import printArea from '../../../components/PrintVendorStock'

import { getClient } from '../../../network/client'
import { select, affirm, continueInput, save } from '../../../network/customerOrderTotal'
import { getSystemConfig } from '../../../network/operatoryCommand'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'

import XLSX from "xlsx"
import FileSaver from "file-saver"

export default {
  name: 'client_order_goods_vo',
  mixins: [today,enterUp],
  components:{
    footView,
    newAdd,
    verifyPassword,
    changeOd,
    printArea
  },
  created(){
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let jxAgentVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null
   if(jxAgentVal){
    this.jxAgent = jxAgentVal[1] == 1 ? true : false
   }
    
    this.inpList = this.getInput()
    // 随机数赋值
    this.pageSession = Math.ceil(Math.random()*1000000)+''

    this.Hlist = this.Hlist1
    // 获取所有客户信息
    getClient({limit:99999}).then(res => {
      console.log(res)
      if (res.data.code == 200) {
        this.newSend()
        let list = res.data.data
        list.forEach(e => {
          if(e.stop != 1){
            this.customerList.push({value:e.no,label:e.name})
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              this.customerName = i.value
              break
            }
          }
        }
      }
      if (this.$route.query.oid) {
        this.sequence = this.$route.query.oid
        select({orderSequence: this.sequence}).then(res => {
          this.newadd = true
          let list = res.data.data.customerOrderVOListInfo
          this.customerNo = list[0].customerNo
          this.inputDate = list[0].orderTime.slice(0,10)
          this.cooperateWay = list[0].cooperateWay
          this.remark = list[0].remark

          this.customerNoBlur()

          this.kindsNumberList = list
          this.kindsNumberList.sort((a,b) => {
            return a.kindsNumber.localeCompare(b.kindsNumber)
          })
          this.total = 0
          this.kindsNumberList.forEach(e => {
            e.colorNoName = e.colorNo + '.' + e.colorName
            this.total += Number(e.number)
          })

          this.tableData = this.kindsNumberList
          this.conversionList(this.kindsNumberList)
        })
      }
    })

    getSystemConfig().then(res => {
      // console.log(res)
      if (res.data.data) {
        this.companyName = res.data.data.companyName
        this.companyPhone = res.data.data.phone
      }
    })
  },
  data(){
    return{
      inpList: [],
      showChangeOd: false,
      showpwd: false,
      newadd: false,
      readOnly: false,

      pageSession: '',

      sendData: {},

      cooperateWay: '配货',
      cooperateWayList: [
        {value:'配货',label:'配货'},
        {value:'订货',label:'订货'},
        {value:'订断',label:'订断'},
        {value:'追断',label:'追断'}
      ],
      customerNo: '',
      customerName: '',
      customerList: [],
      inputDate: this.searchDate(),
      sequence: '',
      remark: '',
      checked: false,
      tableData: [],
      kindsNumberList: [],
      styleNumberList: [],
      // amount: 0,
      Hlist: [],
      Hlist1: [
        {prop:'mnemonicCode',label:'助记码',width:'80'},
        {prop:'kindsNumber',label:'货号',width:'160'},
        {prop:'colorNo',label:'色号',width:''},
        {prop:'colorName',label:'颜色',width:''},
        {prop:'size',label:'尺码编号',width:''},
        {prop:'number',label:'数量',width:''},
        {prop:'sellingPrice',label:'售价',width:''},
        {prop:'discount',label:'折数',width:''},
        {prop:'onePrice',label:'单价',width:''},
        {prop:'money',label:'金额',width:''},
        {prop:'commodityName',label:'品名',width:'140'},
        {prop:'brandedName',label:'品牌',width:'140'},
        {prop:'enteringTime',label:'录入日期',width:'180'}
      ],
      Hlist2:[{prop:'styleNumber',label:'款号',width:'160'},
        {prop:'colorNo',label:'色号',width:''},
        {prop:'colorName',label:'颜色',width:''},
        {prop:'c05',label:'05-XS',width:'65',isShow:true},
        {prop:'c07',label:'07-S',width:'65',isShow:true},
        {prop:'c09',label:'09-M',width:'65',isShow:true},
        {prop:'c11',label:'11-L',width:'65',isShow:true},
        {prop:'c13',label:'13-XL',width:'65',isShow:true},
        {prop:'c15',label:'15-2L',width:'65',isShow:true},
        {prop:'c17',label:'17-3L',width:'65',isShow:true},
        {prop:'c19',label:'19-4L',width:'65',isShow:true},
        {prop:'c21',label:'21-5L',width:'65',isShow:true},
        {prop:'f',label:'F',width:'65',isShow:true},
        {prop:'total',label:'小计',width:''},
        {prop:'sellingPrice',label:'售价',width:''},
        {prop:'sellingPriceMoney',label:'金额',width:''}],

      isConfirm: false,

      // operator: this.getCookie('jxUser'),
      // jxQuarter: this.getCookie('jxQuarter'),
      // jxAgent: this.getCookie('jxAgent') == '1',
      // operator:document.cookie.match(RegExp('jxUser'+'=([^;]+)'))[1],
      // jxQuarter:document.cookie.match(new RegExp("jxQuarter" + name + "=([^;]*)(;|$)"))[1],
      // jxAgent:document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,
      jxQuarter: null,
      jxAgent:null,
      operator:null,
      // 打印
      styleList: [],
      printTotal: 0,
      printMoney: 0,
      // 款号合计
      printStyle: 0,
      // 售价合计
      printSellingPrice: 0,
      // 客户
      printVendor: '',
      printVendorName: '',
      principal: '',
      phone: '',
      cellphone: '',
      address: '',
      companyName: '',
      companyPhone: '',
      printDate: this.searchDate(),
      total: 0
    }
  },
  methods:{
    create(){
      this.newadd = true
      this.readOnly = false
      if (!this.$route.query.oid) {
        if (this.isConfirm) this.isConfirm = false
        this.sequence = ''
        this.tableData = []
        this.total = 0
        this.kindsNumberList = []
        this.styleNumberList = []
      }
    },

    // 数据变动
    newSend(){
      this.sendData = {
        inputDate:this.inputDate,
        customerNo:this.customerNo,
        customerName:this.customerName,
        customerList: this.customerList,
        inputSequence:this.inputSequence,
        sequence:this.sequence,
        warehouseNo:this.warehouseNo,
        warehouseName:this.warehouseName,
        warehouseList:this.warehouseList,
        discount:this.discount,
        cooperateWay:this.cooperateWay,
        remark:this.remark
      }
    },

    showRevision(data){
      this.showpwd = false
      this.showChangeOd = true
    },
    closeChangeOd(){
      this.showChangeOd = false
    },
    saveAdd(a){
      // console.log(a)
      this.readOnly = true
      this.isConfirm = false

      if (a.sequence) {
        this.inputDate = a.inputDate
        this.customerNo = a.customerNo
        this.customerName = a.customerName
        this.cooperateWay = a.cooperateWay
        this.remark = a.remark
        this.sequence = a.sequence
        this.getData()
      }
    },
    // 确认
    Affirm(){
      if (!this.sequence) return
      affirm({sequence:this.sequence}).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '确认成功',
            type: 'success'
          })
          this.isConfirm = true
        } else {
          this.$message.error('确认失败')
        }
      })
    },

    // 客户编号失去焦点
    customerNoBlur(){
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },

    conversionList(list){
      this.styleNumberList = []
      let sn = 0
      let cn = 0

      // 款号颜色
      for (const i of list) {
        if (!this.styleNumberList.length) {
          // 空数组直接添加
          this.styleNumberList.push({
            styleNumber: i.styleNumber,
            colorNo: i.colorNo,
            colorName: i.colorName,
            c05: 0,
            c07: 0,
            c09: 0,
            c11: 0,
            c13: 0,
            c15: 0,
            c17: 0,
            c19: 0,
            c21: 0,
            c23: 0,
            f: 0,
            total: 0,
            sellingPrice: i.sellingPrice,
            onePrice: i.onePrice,
            commodityName: i.commodityName,
            brandedName: i.brandedName,
            quarter: i.quarter,
            tagPrice: i.sellingPrice
          })
          continue
        }
        for (const j of this.styleNumberList) {
          if (j.styleNumber == i.styleNumber) {
            sn = 1
            // 货号存在，判断颜色有没有
            for (const k of this.styleNumberList) {
              if (i.styleNumber == k.styleNumber && i.colorName == k.colorName) {
                cn = 1
                break
              }
              cn = 0
            }
            if(cn) break
          }
          sn = 0
        }
        
        if (!sn || !cn) {
          // 货号或当前货号的颜色不存在，直接添加
          this.styleNumberList.push({
            styleNumber: i.styleNumber,
            colorNo: i.colorNo,
            colorName: i.colorName,
            c05: 0,
            c07: 0,
            c09: 0,
            c11: 0,
            c13: 0,
            c15: 0,
            c17: 0,
            c19: 0,
            c21: 0,
            c23: 0,
            f: 0,
            total: 0,
            sellingPrice: i.sellingPrice,
            onePrice: i.onePrice,
            commodityName: i.commodityName,
            brandedName: i.brandedName,
            quarter: i.quarter,
            tagPrice: i.sellingPrice
          })
        }
      }

      // 数量赋值
      list.forEach(e => {
        // console.log(e)
        for (const i of this.styleNumberList) {
          if (e.styleNumber == i.styleNumber && e.colorName == i.colorName ) {
            i[e.relevanceSize] = i[e.relevanceSize]+e.number
            break
          }
        }
      })

      // 计算总数
      this.styleNumberList.forEach(e => {
        e.total = e.c05 + e.c07 + e.c09 + e.c11 + e.c13 + e.c15 + e.c17 + e.c19 + e.c21 + e.c23 + e.f
        e.sellingPriceMoney = e.sellingPrice*e.total
        e.money = e.onePrice*e.total
        if (e.c05 === 0) e.c05 = ''
        if (e.c07 === 0) e.c07 = ''
        if (e.c09 === 0) e.c09 = ''
        if (e.c11 === 0) e.c11 = ''
        if (e.c13 === 0) e.c13 = ''
        if (e.c15 === 0) e.c15 = ''
        if (e.c17 === 0) e.c17 = ''
        if (e.c19 === 0) e.c19 = ''
        if (e.c21 === 0) e.c21 = ''
        if (e.c23 === 0) e.c23 = ''
        if (e.f === 0) e.f = ''
      })
    },

    readExcel(e){
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        this.$refs.upload1.value = ""
        this.$refs.upload2.value = ""
        return
      }

      const files = e.target.files
      console.log(files)
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx|csv)$/.test(files[0].name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx或者csv格式")
        return false
      }
      
      this.tmpKindsNumberList = []
      let lastKN = []

      if (this.kindsNumberList.length) {
        this.kindsNumberList.forEach(e => {
          console.log(e)
          e.sequence = this.sequence
          lastKN.push(e)
        })
      }
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: "binary"
          })
          const wsname = workbook.SheetNames[0]  //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname],'gb2312')   //生成json表格内容
          // const ws1 = XLSX.decode(Buffer.from([workbook.Sheets[wsname]], 'hex'), 'utf-8')
          console.log(ws)

          let kindsNumberNumMap = {}
          ws.forEach(e => {
            kindsNumberNumMap[e.货号] = e.数量
          })
          console.log(kindsNumberNumMap)
          // return
          
          this.$refs.upload1.value = ""
          this.$refs.upload2.value = ""

          // 是否有信息变动
          let isNew = false
          
          if (JSON.stringify(this.originalData) == '{}') {
            // 第一次，记录原始数据
            this.originalData.inputDate = this.inputDate
            this.originalData.customerNo = this.customerNo
            this.originalData.cooperateWay = this.cooperateWay
            this.originalData.remark = this.remark
          } else {
            // 判断是否修改了数据
            for (const key in this.originalData) {
              if (this.originalData.hasOwnProperty(key)) {
                const e = this.originalData[key]
                if (e != this[key]) {
                  // 修改了数据 重新赋值
                  isNew = true
                  this.originalData.inputDate = this.inputDate
                  this.originalData.customerNo = this.customerNo
                  this.originalData.cooperateWay = this.cooperateWay
                  this.originalData.remark = this.remark
                  break
                }
              }
            }
          }

          if (this.sequence != '' && !isNew) {
            // 有序号并且信息没改，再点读卡，传右表
            // console.log('没有数据变动')
          } else {
            // console.log('第一次或有数据变动')
            // 有数据变动，进厂序号改空
            this.sequence = ''
            this.tableData = []
            this.total = 0
            this.kindsNumberList = []
            this.styleNumberList = []
          }


          let d = {
            orderTime: this.inputDate,
            customerNo: this.customerNo,
            orderSequence: this.sequence,
            cooperateWay: this.cooperateWay,
            receiptsNumber: this.receiptsNumber,
            remark: this.remark,
            kindsNumberNumMap
          }
          console.log(d)
          // return
          continueInput(JSON.stringify(d)).then(res => {
            console.log(res)
            if (res.data.code == 200) {
              if (res.data.data && res.data.data.length) {
                this.sequence = res.data.data[0].sequence
                let isReplenishment = this.kindsNumberList.length ? 1 : 0
                if (this.kindsNumberList.length) {
                  res.data.data.forEach(e => {
                    let exist = 0
                    for (const i of this.kindsNumberList) {
                      if (i.kindsNumber == e.kindsNumber) {
                        i.sum += Number(e.sum)
                        i.number = i.sum
                        exist = 1
                        break
                      }
                    }
                    if (!exist) {
                      this.kindsNumberList.push(e)
                    }
                  })
                } else {
                  this.kindsNumberList = res.data.data
                }
                // 货号：数量 map集合
                let kindsNumberNumMap = {}
                // 补单新货号对象集合 
                let replenishmentNewKindsNumberMap = {}

                this.kindsNumberList.forEach(e => {
                  e.orderSalesSequence = this.sequence
                  kindsNumberNumMap[e.kindsNumber] = e.sum
                  replenishmentNewKindsNumberMap[e.kindsNumber] = e
                })

                if (isReplenishment) {
                  // 补单
                  for (const i of lastKN) {
                    // console.log(i)
                    for (const k in kindsNumberNumMap) {
                      if (kindsNumberNumMap.hasOwnProperty(k)) {
                        if (i.kindsNumber == k) {
                          // delete kindsNumberNumMap[k]
                          delete replenishmentNewKindsNumberMap[k]
                          break
                        }
                      }
                    }
                  }
                }
                let d1 = {
                  customerDTO: {
                    // 是否是补单（补货数据（0否 1是））
                    isReplenishment,
                    orderTime: this.inputDate,
                    customerNo: this.customerNo,
                    sequence: this.sequence,
                    cooperateWay: this.cooperateWay,
                    receiptsNumber: this.receiptsNumber,
                    remark: this.remark,
                    kindsNumberNumMap,
                    replenishmentNewKindsNumberMap
                  },
                  validList: isReplenishment ? lastKN : this.kindsNumberList
                }
                console.log(d1)
                save(JSON.stringify(d1)).then(r => {
                  console.log(r)
                  if (r.data.code == 200) {
                    this.getData()
                    this.$message.success('导入成功')
                  } else {
                    this.$message.error('导入失败')
                  }
                })
              }
            }
          })
        } catch (error) {
          console.log(error)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

    dele(){
      if (!this.sequence) return
      this.$router.push({path: '/delete_document', query: {type: 7,sequence: this.sequence}})
      this.$store.commit('addNav',{label:'客户订货删单',name:'delete_document'})
    },

    // 列印
    printConfirm(){
      // console.log('点击确定了')
      this.clearPrintTable()
      this.styleList = []
      this.printTotal = 0
      this.printMoney = 0
      this.printStyle = 0
      this.printSellingPrice = 0

      this.$confirm('是否使用A4纸打印', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        // 用A4纸
        // console.log('用A4纸')
        this.openPrint(true)
      }).catch(action => {
        // 用半张A4纸  
        if (action == 'cancel') {
          // console.log('用半张A4纸')
          this.openPrint(false)
        }
      })
    },
    openPrint(isA4, x=1, id='printTable'){
      let index = --x
      let printTable = document.getElementById(id)
      let length = this.styleNumberList.length
      
      for (index; index < length; index++) {
        const e = this.styleNumberList[index]
        // console.log(index)
        // console.log(index+1)
        this.printTotal += Number(e.total)
        this.printMoney += Number(e.money)
        this.printSellingPrice += Number(e.sellingPriceMoney)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index+1
        row.insertCell(1).innerHTML = e.styleNumber + '-' + e.colorNo
        row.insertCell(2).innerHTML = e.colorName
        row.insertCell(3).innerHTML = e.commodityName
        row.insertCell(4).innerHTML = e.c05
        row.insertCell(5).innerHTML = e.c07
        row.insertCell(6).innerHTML = e.c09
        row.insertCell(7).innerHTML = e.c11
        row.insertCell(8).innerHTML = e.c13
        row.insertCell(9).innerHTML = e.c15
        row.insertCell(10).innerHTML = e.c17
        row.insertCell(11).innerHTML = e.c19
        row.insertCell(12).innerHTML = e.c21
        row.insertCell(13).innerHTML = e.c23
        row.insertCell(14).innerHTML = e.f
        row.insertCell(15).innerHTML = e.total
        row.insertCell(16).innerHTML = e.sellingPrice
        row.insertCell(17).innerHTML = e.sellingPriceMoney

        if (isA4) {
          if (parseInt((index+1)/33) && (index+1)%33 == 0 && (index+1) != length) {
            // console.log('33倍数')
            let pageIndex = index + 3 - (parseInt(index/33)*33)
            // console.log(pageIndex)
            // console.log(index+1)    // 33
            // console.log(length)     // 36
            let startingPoint = index - 32
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add("addPrintHead")
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${(index+1)/33 * 29.7 + 3}cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户订货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
                <p style="margin: 5px 0;">联系人：${this.principal}</p>
                <p style="margin: 5px 0;">订货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户电话：${this.phone}</p>
                <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
                <p style="margin: 5px 0;">订货日期：${this.printDate}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index+1)/33}`
            // console.log(tableId)
            let tableDom = document.createElement("table")
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                  <td rowspan="2" style="text-align: center;">金额</td>
                </tr>
                <tr>
                  <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="text-align: center;border-top: 1px dotted;">S</td>
                  <td style="text-align: center;border-top: 1px dotted;">M</td>
                  <td style="text-align: center;border-top: 1px dotted;">L</td>
                  <td style="text-align: center;border-top: 1px dotted;">XL</td>
                  <td style="text-align: center;border-top: 1px dotted;">2L</td>
                  <td style="text-align: center;border-top: 1px dotted;">3L</td>
                  <td style="text-align: center;border-top: 1px dotted;">4L</td>
                  <td style="text-align: center;border-top: 1px dotted;">5L</td>
                  <td style="text-align: center;border-top: 1px dotted;">6L</td>
                  <td style="text-align: center;border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(true,index+2,tableId)
            return
          }
          if ((index+1) == length) {
            let pageIndex = index + 3 - (parseInt(index/33)*33)
            // console.log('最后一行')
            let startingPoint = index < 33 ? 0 : parseInt(index/33)*33
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        } else {
          if (parseInt((index+1)/12) && (index+1)%12 == 0 && (index+1) != length) {
            // console.log('12倍数')
            let pageIndex = index + 3 - (parseInt(index/12)*12)
            // console.log(pageIndex)
            // console.log(index+1)    // 12
            // console.log(length)     // 36
            let startingPoint = index - 11
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add("addPrintHead")
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${(index+1)/12 * 14.85 + 3}cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户订货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
                <p style="margin: 5px 0;">联系人：${this.principal}</p>
                <p style="margin: 5px 0;">订货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户电话：${this.phone}</p>
                <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
                <p style="margin: 5px 0;">订货日期：${this.printDate}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index+1)/12}`
            // console.log(tableId)
            let tableDom = document.createElement("table")
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                  <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                  <td rowspan="2" style="text-align: center;">金额</td>
                </tr>
                <tr>
                  <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="text-align: center;border-top: 1px dotted;">S</td>
                  <td style="text-align: center;border-top: 1px dotted;">M</td>
                  <td style="text-align: center;border-top: 1px dotted;">L</td>
                  <td style="text-align: center;border-top: 1px dotted;">XL</td>
                  <td style="text-align: center;border-top: 1px dotted;">2L</td>
                  <td style="text-align: center;border-top: 1px dotted;">3L</td>
                  <td style="text-align: center;border-top: 1px dotted;">4L</td>
                  <td style="text-align: center;border-top: 1px dotted;">5L</td>
                  <td style="text-align: center;border-top: 1px dotted;">6L</td>
                  <td style="text-align: center;border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(false,index+2,tableId)
            return
          }
          if ((index+1) == length) {
            let pageIndex = index + 3 - (parseInt(index/12)*12)
            // console.log('最后一行')
            let startingPoint = index < 12 ? 0 : parseInt(index/12)*12
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += Number(this.styleNumberList[j].total)
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        }

        this.printStyleCount(e.styleNumber)
      }

      this.printStyle = this.styleList.length
      // console.log(this.styleList)
      let int = setInterval(() => {
        if (this.printStyle) {
          clearInterval(int)
          let printHtml = document.getElementById('p').innerHTML
          let wind = window.open("",'newwindow', 'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
          wind.document.body.innerHTML = printHtml
          let style = document.createElement('style')
          style.type = 'text/css'
          style.innerHTML = resources.printCSS
          wind.document.head.appendChild(style)
          wind.print()
          return false
        }
      }, 500)
    },
    clearPrintTable(){
      let printTable = document.getElementById("printTable")
      let trs = printTable.getElementsByTagName("tr")
      let len = trs.length - 1
      for(let i = len; i > 1; i--) {
        printTable.deleteRow(i)
      }

      let printArea = document.getElementById("p")
      let tables = printArea.getElementsByTagName('table')
      len = tables.length
      for (let i = 1; i < len; i++) {
        tables[1].remove()
      }
      let addPrintHeads = document.getElementsByClassName('addPrintHead')
      len = addPrintHeads.length
      for (let i = 0; i < len; i++) {
        addPrintHeads[0].remove()
      }
    },
    printStyleCount(s){
      if (!this.styleList.length) {
        this.styleList.push(s)
      } else {
        let exist = 0
        for (const i of this.styleList) {
          // console.log(i)
          if (i == s) {
            exist = 1
            break
          }
        }
        if (!exist) {
          this.styleList.push(s)
        }
      }
    },
    // insertAfter(p,header1) // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法
    insertAfter( newElement, targetElement ){ // newElement是要追加的元素 targetElement 是指定元素的位置
      let parent = targetElement.parentNode // 找到指定元素的父节点
      if( parent.lastChild == targetElement ){ // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
        parent.appendChild( newElement, targetElement )
      }else{
        parent.insertBefore( newElement, targetElement.nextSibling )
      }
    },

    getSummaries(param){
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map(item => Number(item[prop]))
        if (!values.every(value => isNaN(value))) {
          if (prop == 'c05' || prop == 'c07' || prop == 'c09' 
          || prop == 'c11' || prop == 'c13' || prop == 'c15' 
          || prop == 'c17' || prop == 'c19' || prop == 'c21' 
          || prop == 'c23' || prop == 'f' || prop == 'total' 
          || prop == 'number' || prop == 'sellingPriceMoney' || prop == 'money') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      return sums
    },

    newNo(){
      if (this.$route.query.oid || this.readOnly) return
      this.sequence = ''
      this.tableData = []
      this.total = 0
      this.kindsNumberList = []
      this.styleNumberList = []
    },

    getData(){
      select({
        orderSequence: this.sequence
      }).then(res => {
        this.readOnly = false
        if (res.data.code == 200) {
          this.checked = false
          this.kindsNumberList = res.data.data.customerOrderVOListInfo
          this.kindsNumberList.sort((a,b) => {
            return a.kindsNumber.localeCompare(b.kindsNumber)
          })
          this.total = 0
          this.kindsNumberList.forEach(e => {
            e.colorNoName = e.colorNo + '.' + e.colorName
            e.sum = e.number
            this.total += Number(e.sum)
          })
          this.tableData = this.kindsNumberList
          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })
          this.conversionList(this.kindsNumberList)
        }
      })
    }
  },
  watch:{
    checked(a,b){
      if(a){
        this.Hlist = this.Hlist2
        this.tableData = this.styleNumberList
      }else{
        this.Hlist = this.Hlist1
        this.tableData = this.kindsNumberList
      }
    },
    inputDate(a,b){
      this.newNo()
      this.newSend()
    },
    customerNo(a,b){
      this.newNo()
      this.customerNo = a.toUpperCase().trim()
      this.newSend()
      this.printVendor = a
      getClient({no:a}).then(res => {
        this.principal = res.data.data[0].principal || res.data.data[0].name
        this.cellphone = res.data.data[0].phone || ''
        this.phone = res.data.data[0].cellphone || ''
        this.address = res.data.data[0].address || ''
        this.printVendorName = res.data.data[0].no + '_' + res.data.data[0].name
      })
    },
    cooperateWay(a,b){
      this.newNo()
      this.newSend()
    },
    remark(a,b){
      this.newNo()
      this.newSend()
    },
    $route(a,b) {
      this.newSend()
      if (b.path.indexOf('delete_document') != -1) {
        this.sequence = ''
        this.tableData = []
        this.total = 0
        this.kindsNumberList = []
        this.styleNumberList = []
        return
      }
      if (a.path.indexOf('client_order_goods_vo') != -1) {
        this.inpList = this.getInput()
      }
    }
  }
}
</script>